/**
 * Created by Jackie on 2016/11/10.
 */



function Prizes() {
    this.dom=null;
    this.runningTop=0;
    this.split=0;
    this.timerList=[];

    this.currentId='';

    this.timeMacCount=130;

    this.finishCallBack=null;

    this.height=0;

    this.isRunning=false;

}


$.extend(Prizes.prototype, {

    init:function(dom,button,touchCallBack,finishCallBack){
        var self=this;
        this.dom=dom;
        this.finishCallBack=finishCallBack;

        this.height=$((dom.children())[0]).height();

        this.split=this.height/10;

        $(button).on('touchstart', function(){
            if (self.isRunning) return
            if(touchCallBack!=null && typeof(touchCallBack)=='function')
                touchCallBack();

        })
    },

    start:function(){
        this.isRunning=true;
        this.currentId='';
        var self=this;
        var timer=setInterval(function(){
            self.checking();
        },100);
        this.timerList.push(timer);
    },

    checking:function(){
        var top=parseInt(this.dom.css('top').replace('px',''));
        top-=1;
        var subDom=this.checkSubDom(top);
        if(subDom){
            //到达某个对象了
            if(this.currentId==subDom.attr('id')){       //如果是中了这个对象
                var i=0;
                var length=this.timerList.length;
                for(i=0;i<length;i++){
                    var timer=this.timerList[0];
                    this.timerList.splice(0,1);
                    clearInterval(timer);
                    if(i==50)break;
                }

                if(this.timerList.length<1){
                    //反馈结果
                    this.isRunning=false;
                    if(this.finishCallBack!=null && typeof(this.finishCallBack)=='function'){
                        this.finishCallBack(subDom.attr('data-name'));
                    }
                }
            }

        }
        else if(top+this.dom.height()<=this.height*2){  //要退到最后一个了
            top=0;
        }
        this.dom.css('top',top+'px');

        if(this.currentId.length<1 && this.timerList.length<this.timeMacCount){
            this.start();
        }
    },

    checkSubDom:function(top){
        if(top % this.height==0){
            var sel=Math.abs(top/this.height);
            return $((this.dom.children())[sel]);
        }
        return null;
    },

    stop:function(id){
        var self=this;
        self.currentId=id;
        if(self.currentId==''){
            self.currentId=$((this.dom.children())[0]).attr('id');
        }
    }

})

var prizes = new Prizes()
